<template>
  <div class="upload">
    <!-- :action="uploadFileUrl" -->
    <!-- :show-file-list="false" -->
    <!-- multiple -->
    <el-upload
      
      action=""
      v-loading="loading"
      :http-request="handleUpload"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :headers="headers"
      ref="fileUpload"
    >
      <div class="upload-content">
        <svg-icon
          class-name="search-icon"
          icon-class="upload"
        />
        <!-- <div class="el-upload__tip" slot="tip">
          只能上传jpg/png文件，且不超过500kb
        </div> -->
        <!-- 上传按钮 -->
        <el-button class="upload-button" size="mini" type="primary"
          >请点击此处进行文件上传</el-button
        ><br />
        <!-- 上传提示 -->
        <div
          class="el-upload__tip"
          slot="tip"
          v-if="showTip"
          style="font-size: 20px"
        >
          请上传单个文件
          <template v-if="fileSize">
            大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>,
          </template>
          <template v-if="fileType">
            上传的文件格式仅支持
            <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
          </template>
          的文件
        </div>
      </div>
    </el-upload>

    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul"
    >
      <li
        :key="file.url"
        class="el-upload-list__item ele-upload-list__item-content"
        v-for="(file, index) in fileList"
      >
        <el-link
          :href="`${baseUrl}${file.url}`"
          :underline="false"
          target="_blank"
        >
          <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
        </el-link>
        <div class="ele-upload-list__item-content-action">
          <el-link :underline="false" @click="handleDelete(index)" type="danger"
            >删除</el-link
          >
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { dataPackageUpload } from "@/api/product/productInfo";

import request from "@/utils/request";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 50,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 15000,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["zip"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      loading: false,
      uploadFileList: [],
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 上传文件
    handleUpload(file) {
      let formData = new FormData();
      formData.append("uploadFile", file.file);
      let startTime;
      this.loading = true
      request({
        url: "/lfs-admin/dataPackage/upload",
        method: "post",
        timeout: 0,
        data: formData,
        onUploadProgress: (progressEvent) => {
          if (!startTime) {
            startTime = Date.now(); // 记录开始时间
          } else {
            const currentTime = Date.now(); // 获取当前时间
            const elapsedTime = (currentTime - startTime) / 1000; // 计算已过秒数
            const speedKB = (progressEvent.loaded / 1024 / elapsedTime).toFixed(
              2
            ); // KB/s
            const sppedMB = (speedKB / 1024).toFixed(2);
            if (speedKB >= 1024) {
              console.log(`上传速度: ${sppedMB} MB/s`);
            } else {
              console.log(`上传速度: ${speedKB} KB/s`);
            }
          }
        },
      })
        .then((res) => {

          this.loading = false
          console.log("file", file);
          this.uploadFileList.push({
            imgUrl: res.imgUrl,
            name: file.file.name,
            dataSize: Math.ceil(file.file.size / 1024)
          });
          console.log("res", res);
        })
        .catch(() => {
          this.loading = false
        });

      // dataPackageUpload(formData).then(res => {
      //   console.log('res', res);
      // })
    },
    handleEmitData() {
      if (this.uploadFileList.length == 0) {
        this.$message.error("请先上传文件");
        return false;
      }
      this.$emit("send", { uploadFileList: this.uploadFileList });
      return true;
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      console.log("开始上传");
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确，请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件名是否包含特殊字符
      if (file.name.includes(",")) {
        this.$message.error("文件名不正确，不能包含英文逗号!");
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      // console.log("异常")
      // this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`)

    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error("上传文件失败，请重试");
      // this.$modal.closeLoading();
      this.loading = false
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.fileName, url: res.fileName });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        // this.$modal.closeLoading();
        this.loading = false
        this.$message.error(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        // this.$modal.closeLoading();
        this.loading = false
      }
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
};
</script>

<style scoped lang="scss">
.upload-file {
  position: relative;
  padding: 20px;

  .upload {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 600px;
    border: 1px solid #dadada;
    margin: 20px;

    .upload-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 20px;

      .search-icon {
        display: block;
        font-size: 120px;
        color: #16baaa;
      }

      .upload-button {
        border-color: #16baaa;
        background: #16baaa;
        font-size: 20px;
      }
    }
  }
}

.upload-file-uploader {
  bottom: -50px;
  background-color: #fff;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 1750px;
  height: 280px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.next-button {
  display: inline-block;
  vertical-align: middle;
  height: 38px;
  line-height: 38px;
  border: 1px solid transparent;
  padding: 0 18px;
  margin-left: 1575px;
  background-color: #16baaa;
  color: #fff;
  white-space: nowrap;
  text-align: center;
  font-size: 14px;
  border-radius: 2px;
  cursor: pointer;
  -moz-user-select: none;
  -webkit-user-select: none;
}

.next-button-green {
  border-width: 1px;
  border-style: solid;
  border-color: #16baaa !important;
  color: #16baaa !important;
}

.next-buuton-primary {
  border-color: #d2d2d2;
  background: 0 0;
  color: #5f5f5f;
  margin-left: 1575px;
}
</style>